import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { routerRedux } from 'dva/router';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Button, Input, Spin, Table, message, InputNumber, Statistic, Modal, Progress } from 'antd';
import styles from "./index.less";
import { runInThisContext } from 'vm';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter'

const Search = Input.Search;
const FormItem = Form.Item;
class ClusteringProblem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      login: false,
      totala: 0,
      page: 1,
      pageSize: 10,
      similarList: [],
      query: '', // 搜索的关键词
      minWordCount: '', // 最小字数
      maxWordCount: '', // 最大字数
      minAskCount: '',  // 最小询问次数
      maxAskCount: '',  // 最大询问次数
      order: 'questionCount',   // 排序字段
      sort: 'desc',  //  排序方式，asc：升序，desc：降序,
      dxList: [],
      selectedRowKeys: [],
      rightAlist: [],
      rightBlist: [],
      successA: 'success',
      rightCol1: false,
      loginpig: false,
      num: 0,
      percent: 0
    };
  }

  componentDidMount() {
    this.knowledgeQuestionList()
    this.maintainRecommendStatus()
    this.knowledgeRecommendInfo()
  }

  recommendF1 = () => {
    this.setState({ rightCol1: true })
  }

  rightCol1 = () => {
    console.log('打开推荐问题页面')
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    this.props.form.validateFields((err, values) => {// 校验方法
      console.log(userInfo)
      let a =''
      let b =''
      let c =''
      let d =''
      if(userInfo.InputNumber1 !==''){ a =  Number(userInfo.InputNumber1)}
      if(userInfo.InputNumber2 !==''){ b =  Number(userInfo.InputNumber2)}
      if(userInfo.xwcs1 !==''){ c =  Number(userInfo.xwcs1)}
      if(userInfo.xwcs2 !==''){ d =  Number(userInfo.xwcs2)}
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'knowledgeSmartMaintenance/knowledclusterSubmit',
          payload: {
            includeKey: userInfo.bkKeyword,
            notIncludeKey: userInfo.NoKeyword,
            minWordCount: a,
            maxWordCount: b,
            minAskCount: c,
            maxAskCount: d,
          },
          callback: res => {
            if (res.code === 0) {
              console.log('开始推荐问题推荐任务', res);
              message.success(res.msg)
              this.time() // 随时关闭
              this.setState({ loginpig: true })
              this.setState({
                rightCol1: false
              })
            }
          },
        });
      });
    });
  }

  time = () => {
    let { leName } = this.state
    setTimeout(() => {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'knowledgeSmartMaintenance/knowledgeMaintainClusterStatus',
          payload: {},
          callback: res => {
            console.log('获取问题推荐状态', res);
            if (res.status === 'wait') {
              this.setState({ loginpig: true })
              this.percent()
            } else {
              this.setState({ loginpig: false })
              this.knowledgeQuestionList()
              this.maintainRecommendStatus()
              this.knowledgeRecommendInfo()
            }
            this.setState({
              successA: res.status,
              rightAlist: res
            })
          },
        });
      });
    }, 1000)
  }

  rightColNo1 = () => {
    console.log('关闭推荐问题页面')
    this.setState({ rightCol1: false })
  }

  // 进度条任务
  percent = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeclusterProcess',
        payload: {},
        callback: res => {
          console.log('获取任务进度', res);
          if (res.process === 1) {
            this.setState({ num: res.process }, () => {
              this.time()
            })
          } else if (res.process === 0) {
            this.setState({ percent: res.process }, () => {
              setTimeout(() => {
                this.setState({ num: res.process }, () => {
                  this.percent()
                })
              }, 1000)
            })
          } else {
            const number = res.process
            console.log(Math.floor(Number(number * 100)))
            this.setState({ percent: Math.floor(Number(number * 100)) }, () => {
              setTimeout(() => {
                this.setState({ num: res.process }, () => {
                  this.percent()
                })
              }, 1000)
            })
          }
        },
      });
    });
  }

  // 获取问题推荐状态  
  maintainRecommendStatus = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeMaintainClusterStatus',
        payload: {},
        callback: res => {
          console.log('获取问题推荐状态', res);
          if (res.status === 'wait') {
            this.setState({ loginpig: true })
          }
          this.setState({
            successA: res.status,
            rightAlist: res
          })
        },
      });
    });
  }

  // 获取问题推荐信息
  knowledgeRecommendInfo = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendInfoB',
        payload: {},
        callback: res => {
          console.log('获取问题推荐信息', res);
          this.setState({
            rightBlist: res
          })
        },
      });
    });
  }

  knowledgeQuestionList = () => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    const { page, pageSize, query, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendListB',
        payload: {
          query,
          order,
          sort,
          page,
          limit: pageSize,
        },
        callback: res => {
          console.log('问题库列表', res);
          if (res.code === 0) {
            this.setState({
              similarList: res.data.list,
              totala: Number(res.data.total),
              login: false
            })
          }
        },
      });
    });
  }

  pageWay = (a) => {
    console.log(a)
    this.setState({ page: a }, () => {
      this.knowledgeQuestionList()
    })

  }

  onShowSizepageWay = (a, b) => {
    console.log(a, b)
    this.setState({ page: a, pageSize: b }, () => {
      this.knowledgeQuestionList()
    })

  }

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
    // 使用方法 
    // let user  = this.userInfo()
    // console.log(user)
  }



  // 批量删除 忽略回调
  knowledgeQuestionDelete = (ids, url) => {
    if (ids.length === 0) {
      message.error('请先选择需要操作内容')
    } else {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: url,
          payload: {
            ids,
          },
          callback: res => {
            console.log('删除问题库中的问题', res);
            if (res.code === 0) {
              message.success(`${res.msg}`)
              this.setState({
                login: false,
                selectedRowKeys: [],
              }, () => {
                this.knowledgeQuestionList()
                this.knowledgeRecommendInfo()
              })
            }
          },
        });
      });
    }
  }

  deleteTable = (item) => { // knowledgeQuestionDelete
    this.setState({ login: true })
    console.log(item)
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/knowledgeRecommendIgnoreB')
  }

  deleteTables = (item) => {
    this.setState({ login: true })
    console.log(item)
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/knowledgeRecommendIgnoresB')
  }

  handleOpen = (item) => {
    console.log(item)

  }

  // 批量删除
  batchDelete = () => {
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeRecommendIgnoreB')
  }

  // 批量忽略
  moveBlacklist = () => { // questionBlacklistMoveIn
    const { dxList } = this.state
    console.log(dxList)
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeRecommendIgnoresB')
  }

  // 查看
  view = (item, indexs) => {
    const { order, sort, page, pageSize, query } = this.state
    console.log(item, indexs)
    let index = (page - 1) * pageSize + indexs
    let items = item
    items.order = order
    items.sort = sort
    items.index = index
    items.query = query
    console.log(items)
    const { dispatch } = this.props;
    dispatch(routerRedux.push({
      pathname: '/capacity/knowledgeSmartMaintenance/clusterView',
      params: { item: items }
    }));
  }


  // 排序
  pXhandleChange = (pagination, filters, sorter, ) => {
    console.log(sorter) // "ascend" 升序 "descend"降序 参数 order  field->dataIndex
    if (sorter.field) { } else {
      console.log('初始')
      this.setState({
        order: 'questionCount',
        sort: 'desc'
      }, () => {
        this.knowledgeQuestionList()
      })
    }
    if (sorter.field === "questionCount") { // 字数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({
          order: 'questionCount',
          sort: 'asc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({
          order: 'questionCount',
          sort: 'desc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
    }
    if (sorter.field === "askCount") { // 询问次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({
          order: 'askCount',
          sort: 'asc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({
          order: 'askCount',
          sort: 'desc'
        }, () => {
          this.knowledgeQuestionList()
        })
      }
    }

  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {// 文字
        xs: 24,
        sm: 5
      },
      wrapperCol: {// 输入框
        xs: 24,
        sm: 19
      }
    }
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        let a = []
        selectedRows.map((item, index) => {
          a.push(item.id)
        })
        this.setState({ dxList: a, selectedRowKeys, })
      },
    };
    const columns = [
      {
        title: '问题组',
        width: 'calc(30vw)',
        dataIndex: 'std',
        render(item) {
          return (
            <div  dangerouslySetInnerHTML={{ __html: item }}></div>
          )
        }
      },
      {
        title: '问题数量',
        width: 'calc(10vw)',
        sorter: (a, b) => { },
        dataIndex: 'questionCount',
      },
      {
        title: '询问总次数',
        dataIndex: 'askCount',
        sorter: (a, b) => { },
        width: 'calc(10vw)',
      },
      {
        title: '操作',
        width: 'calc(15vw)',
        render: (text, item, index) => {
          return <div className={styles.flexBj}>
            <div
              style={{ marginRight: 10, marginBottom: 4 }}
              className={styles.buttongl}
              onClick={() => { this.deleteTable(item) }}>
              <span><Icon size="small" type="delete" style={{ marginRight: 5 }} />
              </span><span>删除</span>
            </div>

            <div
              style={{ marginRight: 10, marginBottom: 4 }}
              className={styles.buttong3}
              onClick={() => { this.deleteTables(item) }}>
              <span><Icon size="small" type="eye-invisible" style={{ marginRight: 5 }} />
              </span><span>忽略</span>
            </div>

            <div
              style={{ marginRight: 10, marginBottom: 4 }}
              className={styles.buttong4}
              onClick={() => { this.view(item, index) }}>
              <span><Icon size="small" type="eye" style={{ marginRight: 5 }} />
              </span><span>查看</span>
            </div>

          </div>
        }
      },
    ]
    return (
      <Suspense fallback={< PageLoading />} >
        <PageHeaderWrapper>
          <div style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, }} xs={24}>
                <div className={styles.title}>
                  <span>问题聚类</span>
                  <BackRouter pathname='/capacity/knowledgeSmartMaintenance'></BackRouter>
                </div>
              </Col>
            </Row>
            <Card
              bordered={false}
            >
              {this.state.loginpig ? <div className={styles.progrees} style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
                <div style={{ color: '#000' }}>问题推荐中,请稍后再来查看...</div>
                <div style={{ height: 30 }}></div>
                <Progress
                  type="circle"
                  percent={this.state.percent}
                  width={90}
                  strokeWidth={8}
                />
                <div style={{ height: 30 }}></div>
                {/* <Button onClick={this.onClose} type='primary'>关闭</Button> */}
              </div> : <Row>
                  <Row style={{ margin: '10px 0px 40px 0px' }} gutter={100}>
                    <Col span={5}>
                      <Statistic title="问题组数量" value={this.state.rightBlist.groupCount} />
                    </Col>
                    <Col span={5}>
                      <Statistic title="问题数量" value={this.state.rightBlist.itemCount} />
                    </Col>
                    <Col span={5}>
                      <Statistic title="已处理问题数量" value={this.state.rightBlist.handleCount} />
                    </Col>
                    <Col span={5}>
                      <Statistic title="待处理问题数量" value={this.state.rightBlist.waitCount} />
                    </Col>
                    <Col className='buttonYs' style={{ display: 'flex', alignItems: 'center', minHeight: 60 }} span={4}>
                      <Button onClick={this.recommendF1} size='large'>重新聚类</Button>
                    </Col>
                  </Row>
                  <div className={styles.border}></div>
                  <Form style={{ marginBottom: 20 }} layout="inline">
                    <FormItem className='zdyButtonA'>
                      <Button onClick={this.batchDelete} type='primary'>批量删除</Button>
                    </FormItem>
                    <FormItem className='zdyButtonZ'>
                      <Button onClick={this.moveBlacklist} type='primary'>批量忽略</Button>
                    </FormItem>
                    <span style={{ float: "right" }}>
                      <FormItem>
                        {getFieldDecorator('inputA', {
                          initialValue: '',
                        })(
                          <Search
                            placeholder="请输入关键词"
                            onSearch={value => {
                              console.log(value)
                              this.setState({
                                query: value,
                              }, () => {
                                this.knowledgeQuestionList()
                              })
                            }}
                            style={{ width: 325 }}
                          />
                        )}
                      </FormItem>
                    </span>
                  </Form>
                  {/*  style={{display: 'flex',justifyContent:'center'}} */}

                  <Spin spinning={this.state.login}>
                    <Table
                      //  className='zdyTable'
                      rowSelection={rowSelection}
                      onChange={this.pXhandleChange}
                      style={{ padding: '20px 0px 0px 0px' }}
                      columns={columns}
                      dataSource={this.state.similarList}// 数据
                      // onChange={this.handleChange}
                      pagination={{  // 分页
                        total: this.state.totala,
                        pageSize: this.state.pageSize,  // 显示几条一页
                        current: this.state.page, // 当前页
                        showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                        showQuickJumper: true,
                        onChange: this.pageWay,
                        onShowSizeChange: this.onShowSizepageWay
                      }}
                    />
                  </Spin>
                </Row>}
            </Card>
            <Modal
              title="选择待推荐问题"
              okText="确认"
              cancelText="取消"
              visible={this.state.rightCol1}
              onOk={this.rightCol1}
              onCancel={this.rightColNo1}
            >
              <Row>
                <Col span={24}>
                  <p>将问题库中满足以下条件的问题进行问题推荐:</p>
                  <Form layout="horizontal" >
                    <FormItem label='包含关键词' {...FormItemLayont}>
                      {getFieldDecorator('bkKeyword', {
                        initialValue: '',
                      })(
                        <Input placeholder="多个关键字之间用空格分开"></Input>
                      )}
                    </FormItem>
                    <FormItem label='不含关键词' {...FormItemLayont}>
                      {getFieldDecorator('NoKeyword', {
                        initialValue: '',
                      })(
                        <Input placeholder="多个关键字之间用空格分开"></Input>
                      )}
                    </FormItem>
                    <FormItem label='字数' {...FormItemLayont}>
                      {getFieldDecorator('InputNumber1', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                      )}
                      <span>  —  </span>
                      {getFieldDecorator('InputNumber2', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                      )}
                    </FormItem>
                    <FormItem label='询问次数' {...FormItemLayont}>
                      {getFieldDecorator('xwcs1', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                      )}
                      <span>  —  </span>
                      {getFieldDecorator('xwcs2', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                      )}
                    </FormItem>
                    <p style={{ color: '#d3d3d3', marginLeft: 30 }}>若不设置任何条件则将对问题库中所有问题进行推荐</p>
                  </Form>
                </Col>
              </Row>
            </Modal>
          </div>
        </PageHeaderWrapper>
      </Suspense >
    );
  }


}

export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(ClusteringProblem));